#!/usr/bin/env python3
"""
简化版本的 FastAPI 应用，仅用于测试 Discourse 功能
"""

from fastapi import FastAPI, HTTPException, Query
from typing import List
import sys
import os

# 添加项目根目录到 Python 路径
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from app.services.discourse import DiscourseService
from app.config import settings

app = FastAPI(title="Discourse API Test", version="1.0.0")

# 创建 Discourse 服务实例
discourse_service = DiscourseService(
    base_url=settings.DISCOURSE_BASE_URL,
    api_key=settings.DISCOURSE_API_KEY,
    username=settings.DISCOURSE_USERNAME
)

@app.get("/")
async def root():
    """根路径"""
    return {"message": "Discourse API Test Server", "status": "running"}

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "discourse-api-test"}

@app.get("/discourse/posts/by-tags")
async def search_posts_by_tags(
    tags: List[str] = Query(..., description="标签列表"),
    limit: int = Query(20, ge=1, le=100),
):
    """通过标签搜索帖子"""
    try:
        posts = await discourse_service.search_posts_by_tags(tags=tags, limit=limit)
        return {
            "tags": tags,
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/discourse/posts/with-any-tags")
async def get_posts_with_any_tags(
    tags: List[str] = Query(..., description="标签列表（OR 查询）"),
    limit: int = Query(20, ge=1, le=100),
):
    """获取包含任意指定标签的帖子（OR 查询）"""
    try:
        posts = await discourse_service.get_posts_with_any_tags(tags=tags, limit=limit)
        return {
            "tags": tags,
            "query_type": "OR",
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/discourse/posts/with-all-tags")
async def get_posts_with_all_tags(
    tags: List[str] = Query(..., description="标签列表（AND 查询）"),
    limit: int = Query(20, ge=1, le=100),
):
    """获取包含所有指定标签的帖子（AND 查询）"""
    try:
        posts = await discourse_service.get_posts_with_all_tags(tags=tags, limit=limit)
        return {
            "tags": tags,
            "query_type": "AND",
            "posts": posts,
            "count": len(posts),
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001)
